package com.miaomiaomiao.gegege.service;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service("picService")
public class PicService {
	
	@Resource(name="jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 
	 * @param is
	 * 
	 * 
	 * 
	 * 
	 */
	public long up(final byte[] content) {
		
		final String sql = "insert into tb_pic (picblob) values (?)";
/*		final LobHandler lobHandler = new DefaultLobHandler();
		long id = jdbcTemplate.execute(sql, new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
			@Override
			protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException, DataAccessException {
				lobCreator.setBlobAsBytes(ps, 1, content);
			}
		});*/
		
		KeyHolder keyHolder = new GeneratedKeyHolder();  
		jdbcTemplate.update(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
		        PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); 
		        ps.setBytes(1, content);
		        return ps;  
			}  

		}, keyHolder);  
		
		long id = keyHolder.getKey().longValue();  

		return id;
	}
	
	
	public byte[] q(final long id) {
		final String sql = "select id, picblob from tb_pic where id=?";
		byte[] bb;
		
		bb = jdbcTemplate.query(sql, new PreparedStatementSetter() {
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setLong(1, id);
			}
		}, new ResultSetExtractor<byte[]>() {
			public byte[] extractData(ResultSet rs) throws SQLException, DataAccessException {
				rs.next();
				return rs.getBytes(2);
			}
		});
		
  		return bb;
	}
	
}



